<template>
	<div class="space"></div>

	<van-checkbox-group v-model="checked">
		<van-swipe-cell v-for="(item, index) in data" :key="item.id" class="item">
			<van-checkbox class="checkbox" :name="item.id"></van-checkbox>
			<van-card
				:price="item.total.toFixed(2)"
				:title="item.product.name"
				:desc="'库存：' + item.product.stock"
				class="goods-card"
				:thumb="item.product.thumbs_text[0]"
				@click-thumb="() => router.push('/product/info?proid=' + item.product.id)">
				<template #num>
					<van-stepper
						v-model="item.nums"
						:long-press="false"
						@change="stepperChange(item.nums, item.id, item.product.id, index)"
						:name="item.id"
						:disabled="isDisabled"
						button-size="20px" />
				</template>
				<template #tags>
					<span class="small">单价：{{ item.product.price }}</span>
				</template>
			</van-card>
			<template #right>
				<van-button square text="删除" type="danger" class="delete-button" @click="del(item.id, index)" />
			</template>
		</van-swipe-cell>
	</van-checkbox-group>

	<van-loading v-if="loading" size="24px" vertical style="margin-top: 20px">加载中...</van-loading>

	<van-submit-bar
		:price="totalPrice * 100"
		button-text="提交订单"
		@submit="onSubmit"
		:disabled="data.length <= 0 || checked.length <= 0">
		<van-checkbox v-model="selectAll" :disabled="data.length <= 0">全选</van-checkbox>
	</van-submit-bar>
</template>

<script setup>
import { showLoadingToast, closeToast } from 'vant';
const { proxy } = getCurrentInstance();

const business = proxy.$cookies.get('business');

const router = useRouter();

const data = ref([]);
const checked = ref([]);
const isDisabled = ref(false);
const loading = ref(true);

// 总价格
const totalPrice = computed(() => {
	return checked.value.reduce((t, v) => {
		const item = data.value.find((a) => a.id === v);

		if (item) {
			t += item.total;
		}

		return t;
	}, 0);
});
// 是否全选
const selectAll = computed({
	get() {
		if (checked.value.length === 0) return false;
		return data.value.every((v) => checked.value.includes(v.id));
	},
	set(val) {
		if (val) {
			checked.value = data.value.map((v) => v.id);
		} else {
			checked.value = [];
		}
	},
});
// 获取数据
const getData = async () => {
	loading.value = true;
	const res = await proxy.$GET({
		url: '/cart/index',
		params: { busid: business.id },
	});

	loading.value = false;

	if (res.code === 0) {
		proxy.$fail(res.msg);
		return;
	}

	data.value = res.data.map((v) => {
		v._nums = v.nums;

		return v;
	});
};
// 数量切换
const stepperChange = async (val, id, proid, index) => {
	if (isDisabled.value) return;

	showLoadingToast({ forbidClick: true });

	const res = await proxy.$POST({
		url: 'cart/edit',
		params: { id, proid, busid: business.id, nums: val },
	});

	if (res.code === 0) {
		closeToast();

		proxy.$fail(res.msg);

		if (index !== -1) {
			isDisabled.value = true;
			nextTick(() => {
				isDisabled.value = false;
			});
			// 还原之前的值
			data.value[index].nums = data.value[index]._nums;
		}

		return;
	}

	if (index !== -1) {
		// 更新值
		data.value[index]._nums = data.value[index].nums;

		data.value[index].total = data.value[index].nums * data.value[index].price;
	}

	getData().then(() => {
		closeToast();
	});
};
// 删除购物车
const del = async (id, index) => {
	proxy
		.$confirm({
			title: '提示',
			message: '确定要删除吗？',
		})
		.then(
			async () => {
				const res = await proxy.$POST({
					url: 'cart/del',
					params: { id, busid: business.id },
				});

				if (res.code === 0) {
					proxy.$fail(res.msg);
					return;
				}

				proxy.$success(res.msg);

				data.value.splice(index, 1);
			},
			() => {}
		);
};
// 提交订单
const onSubmit = async () => {
	const ids = checked.value;

	proxy.$router.push({
		path: '/cart/confirm',
		query: { ids },
	});
};

getData();
</script>

<style scoped>
.goods-card {
	margin: 0;
	background-color: white;
}

.delete-button {
	height: 100%;
}

.small {
	font-size: 12px;
	color: #888;
}

.item {
	/* margin: 0 6px; */
	margin-bottom: 10px;
	background-color: #fff;
}

.item > :deep(.van-swipe-cell__wrapper) {
	position: relative;
}
.item .checkbox {
	position: absolute;
	top: 52px;
	left: 10px;
	z-index: 99;
	transform: translateY(-50%);
}

.item :deep(.van-card) {
	margin-left: 40px;
	padding-left: 0;
}

.item :deep(.van-card__price){
	color: #fe7923;
}
</style>
